package com.feishi.core.util.http;

import org.apache.http.NameValuePair;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @auth caixq
 * @time 17-12-12 16:52
 **/
public class HttpsUtil {



    public static CloseableHttpClient getHttpClient(InputStream ca,InputStream cert,InputStream key) throws CertificateException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
        final char[] KEY_STORE_PASSWORD = "".toCharArray();
        //获取证书地址
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(ca);
        final Certificate clientCert = cf.generateCertificate(cert);
        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(new InputStreamReader(key))
                .readObject();
        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);
        //设置信任的证书
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);
        //设置私钥
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[]{clientCert});
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, null)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD)
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        return  HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
    }

    public static String post(String url, CloseableHttpClient httpclient) throws Exception {
        return post(url,httpclient,null,null,null);
    }
    public static String post(String url, CloseableHttpClient httpclient,String contentStr) throws Exception {
        return post(url,httpclient,null,contentStr,null);
    }
    public static String post(String url, CloseableHttpClient httpclient,String contentStr,Map<String,String> header) throws Exception {
        return post(url,httpclient,null,contentStr,header);
    }
    public static String post(String url, CloseableHttpClient httpclient,Map<String,String> param,String contentStr,Map<String,String> header) throws Exception {
        return HttpUtil.sendRequest(httpclient,HttpUtil.buildPost(url,param,contentStr,header));
    }


    public static String get(String url, CloseableHttpClient httpclient) throws Exception {
        return get(url,httpclient,null,null);
    }
    public static String get(String url, CloseableHttpClient httpclient,Map<String,String> param) throws Exception {
        return get(url,httpclient,param,null);
    }

    private static String get(String url, CloseableHttpClient httpclient, Map<String, String> param, Map<String,String> header) throws Exception {
        return HttpUtil.sendRequest(httpclient,HttpUtil.buildGet(url,param,header));
    }

    private static List<NameValuePair> toNameValueList(Map<String, String> params) {
        // TODO Auto-generated method stub
        if(params==null||params.size()==0){
            return null;
        }
        List<NameValuePair> list=new ArrayList<>();
        for (Map.Entry<String, String> entry:params.entrySet()) {
            list.add(new NameValuePairBase(entry.getKey(), entry.getValue()));
        }
        return list;
    }



}
